package com.yh.serviceimpl;

import com.yh.dao.PermissionDao;
import com.yh.javabean.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class MyInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {
@Autowired
private PermissionDao permissionDao;
private HashMap<String, Collection<ConfigAttribute>> map = null;
  public void loadResourceDefine() {
      map = new HashMap<>();
      Collection<ConfigAttribute> array;
      Controller cfg;
      List<Permission> permissions = permissionDao.selectAll();
      for (Permission permission : permissions){
          array = new ArrayList<>();
          cfg = (Controller) new SecurityConfig(permission.getPermissionName());
          array.add((ConfigAttribute) cfg);
          map.put(permission.getUrl(),array);
      }
  }
}
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
    if (map == null) loadResourceDefine();
    HttpServletRequest request = (HttpServletRequest) ((HttpServletRequest) object).getHttpServletMapping();
    AntPathMatcher matcher;
    String resUrl;
    for (Iterator<String> iter = map.keySet().iterator(); iter.hasNext();){
        resUrl = iter.next();
        matcher = new AntPathMatcher();
        if (matcher.match(resUrl,request.getRequestURI())){
            return map.get(resUrl);
        }
    }
    return null;
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
    return null;
}
@Override
public boolean supports(Class<?> clazz) {
    return true;
}
}